#ifndef     __ARC_H
#define     __ARC_H

#include "./mutex.h"

namespace rtos {

template <typename OPEN, typename CLOSE>
class Arc {

public:
    Arc(const OPEN& open_fn, const CLOSE& close_fn) : m_open_fn(open_fn), m_close_fn(close_fn) {
    }

    void init() {
        m_mutex.init();
    }

    void open() {
        AUTO_LOCK(m_mutex);
        if (m_open_count == 0) {
            m_open_fn();
        }
        m_open_count += 1;
    }

    void close() {
        AUTO_LOCK(m_mutex);
        if (m_open_count == 0) {
            return;
        }
        if (m_open_count == 1) {
            m_close_fn();
        }
        m_open_count -= 1;
    }

private:
    Mutex m_mutex;
    OPEN m_open_fn;
    CLOSE m_close_fn;
    uint32_t m_open_count = 0;
};

}

#endif
